import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { ExceptionHandler } from './handler/exception.handler';
import { TimeoutException, AuthException, BusinessException } from './handler/exception/exception';

@Component({
  selector: 'zepride-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.less']
})
export class AppComponent implements OnInit {

  isCollapsed = false;

  constructor(
    private message: NzMessageService,
    private router: Router
  ) { }

  ngOnInit() {
    this.registerErrorHandler();
  }

  registerErrorHandler() {
    ExceptionHandler.current.handleError = (error) => {
      const msg = this.formatErrorMsg(error);
      this.message.error(msg);
      console.log(error);
    };
  }

  formatErrorMsg(error: any) {
    let msg = '';
    const errorInstance = error.rejection ? error.rejection : error;
    if (errorInstance) {
      if (errorInstance instanceof TimeoutException) {
        msg = error.message;
      } else if (error instanceof AuthException) {
        msg = error.message;
        this.router.navigateByUrl('login');
      } else if (error instanceof BusinessException) {
        msg = error.message;
      } else {
        if (errorInstance.error && errorInstance.error.message) {
          msg = errorInstance.error.message;
        } else {
          msg = errorInstance.message ? errorInstance.message : error;
        }
      }
    } else {
      if (error.error && error.error.message) {
        msg = error.error.message;
      } else {
        msg = error.message ? error.message : error;
      }
    }
    return msg;
  }

}
